const db = require("../db")
var date = require("silly-datetime");
const now = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss');

const _ = require("lodash")

function delayTimes(data, delay) {
    console.log(data);
    data = new Date(data)
    let year = data.getFullYear()
    let month = data.getMonth() + 1
    let day = data.getDate() + delay
    //小月
    if (month == 4 || month == 6 || month == 9 || month == 11) {
        if (day > 30) {
            day -= 30
            month += 1
        }
    }
    //2月
    else if (month == 2) {
        if (isLeapYear(date.getFullYear())) {
            if (day > 29) {
                day -= 29
                month + 1
            } else {
                day -= 28
                month += 1
            }
        }
        if (day > 28) {
            day -= 28
            month += 1
        }
    }
    //大月
    else {
        if (day > 31) {
            day -= 31
            month += 1
        }
    }
    return year + '-' + month + '-' + day
}
//JS判断闰年代码
function isLeapYear(Year) {
    if (((Year % 4) == 0) && ((Year % 100) != 0) || ((Year % 400) == 0)) {
        return (true);
    } else {
        return (false);
    }
}
// 随机生成订单号：时间戳+6位随机数
function orderCode() {
    var orderCode = '';
    for (var i = 0; i < 6; i++) //6位随机数，用以加在时间戳后面。
    {
        orderCode += Math.floor(Math.random() * 10);
    }
    orderCode = new Date().getTime() + orderCode; //时间戳，用来生成订单号。
    return orderCode;
}
// 更新商品总销量
function updateGoodsSale() {
    db.query("select sum(number) as saleCount ,shopId,goodId from user_order group by goodId,shopId;", function (err, result) {
        if (err) return res.cc(err)
        let data = _.groupBy(result, function (n) {
            return n.shopId + "," + n.goodId;
        })
        let str = `update goods set saleCount =  case  `
        let obj = []
        for (item in data) {
            let temp = item.split(',')
            str += `when shopId = ${temp[0]} and id = ${temp[1]} then ${data[item][0].saleCount} `
            obj.push(`(${item})`)
        }
        str += `end where (shopId,id) in (${obj.join(",")})`
    })
}
module.exports = {
    // 获取订单列表
    getAllOrder: (req, res) => {
        let param = req.body
        let sql = `select user_order.id,orderNum,user.username,goods.goodName,user_order.createTime,finishTime,order_status,is_pay,is_deliver from goods,user_order,user where user.id = user_order.userId and user_order.goodId = goods.id and user_order.is_delete =0 order by order_status, createTime,is_pay desc limit ${parseInt((param.page -1)*param.limit)},${param.page*param.limit}`
        // console.log(sql);
        db.query(sql, function (err, result) {
            if (err) return res.cc(err)
            let data = result
            db.query("select count(*) as total from user_order",function(err,result){
                if(err) return res.cc(err)
                return res.send({
                    code: 200,
                    msg: "获取订单列表成功！",
                    data: {
                        total:result[0].total,
                        data:data
                    }
                })
            })

        })
    },
    // 更新发货状态
    changeIsDeliver: (req, res) => {
        let id = req.body.id
        let finishTime = delayTimes(now, 15)
        db.query("update user_order set is_deliver = 1,deliverTime=?,finishTime = ? where id = ?", [now, date.format(finishTime, 'YYYY-MM-DD'), id], function (err, result) {
            if (err) return res.cc(err)
            if (result.affectedRows !== 1) return res.cc("更新发货状态失败！")
            return res.cc("发货成功！", 200)
        })
    },
    // 延长收货时间
    delayTime: (req, res) => {
        let id = req.body.id
        db.query('select finishTime from user_order where id = ?', id, function (err, result) {
            if (err) return res.cc(err)
            let finishTime = delayTimes(result[0].finishTime, 15)
            db.query('update user_order set finishTime = ? where id = ?', [finishTime, id], function (err, result) {
                if (err) return res.cc(err.msg)
                if (result.affectedRows !== 1) return res.cc("延长收货时间失败！")
                return res.cc("延长收货时间成功！", 200)
            })
        })

    },
    //  取消订单
    cancelOrder: (req, res) => {
        let id = req.body.id
        db.query("update user_order set order_status = 2 ,finishTime = ? where id = ?", [now, id], function (err, result) {
            if (err) return res.cc(err)
            if (result.affectedRows !== 1) return res.cc("取消订单失败！")
            return res.cc("取消订单成功！", 200)
        })
    },
    // 删除订单
    delOrder: (req, res) => {
        let id = req.body.id
        db.query("update user_order set is_delete = 1 where id = ?", id, function (err, result) {
            if (err) return res.cc(err)
            if (result.affectedRows !== 1) return res.cc("删除订单失败！")
            return res.cc("删除订单成功！", 200)
        })
    },

    // 创建订单
    createOrder: (req, res) => {
        let tableData = req.body.info
        let userId = req.body.userId
        let str = []
        let updateStr = []
        let orderNum = orderCode()
        tableData.forEach(e => {
            str.push(`('${orderNum}',${e.id},${userId},${e.shopId},${e.number},${e.sum},'${now}',${e.order_sumup})`)
            updateStr.push(`(${userId},${e.shopId},${e.id})`)
        });
        str = str.join(",")
        updateStr.join(',')
        db.query(`insert into user_order(orderNum,goodId,userId,shopId,number,sum,createTime,order_sumup) values ${str}`, function (err, result) {
            if (err) return res.cc(err)
            db.query(`update user_cart set is_delete = 1 where (userId,shopId,goodsId) in (${updateStr}) `, function (err, result) {
                if (err) res.cc(err)
                updateGoodsSale()
                return res.cc("创建订单成功！", 200)
            })

        })
    },

    // 获取用户订单列表
    getUserOrderList: (req, res) => {
        let userId = req.body.id
        db.query("select a.id,a.shopId,a.orderNum,a.number,a.createTime,a.order_status,a.is_pay,a.is_deliver,a.order_sumup,b.goodName,b.priceAgo,b.model,b.price,c.shopName,d.picName from user_order a,goods b,shop c,goods_pic d where userId = ? and a.goodId = b.id and a.shopId = c.id and b.fileId = d.id and a.is_delete = 0 order by a.order_status,a.createTime desc", userId, function (err, result) {
            if (err) return res.cc(err)
            let data = []
            let resByOrderNum = _.groupBy(result, 'orderNum')
            for (item in resByOrderNum) {

                let orderByShop = _.groupBy(resByOrderNum[item], 'shopName')
                for (i2 in orderByShop) {
                    let temp = {
                        'id': resByOrderNum[item][0].id,
                        'orderNum': item,
                        'shopId': orderByShop[i2][0].shopId,
                        'is_pay': orderByShop[i2][0].is_pay,
                        'is_deliver': orderByShop[i2][0].is_deliver,
                        'createTime': resByOrderNum[item][0].createTime.split(" ")[0],
                        'shopName': i2,
                        'order_status': resByOrderNum[item][0].order_status,
                        'list': orderByShop[i2]
                    }
                    data.push(temp)
                }

            }
            return res.send({
                code: 200,
                msg: '获取用户订单成功',
                data: data
            })
        })
    },
    // 确认收货
    change2finish: (req, res) => {
        let info = req.body
        db.query("update user_order set order_status = 1 ,finishTime = ? where userId =? and orderNum = ? and shopId = ?", [now, info.userId, info.orderNum, info.shopId], function (err, result) {
            if (err) return res.cc(err)
            return res.cc("修改状态成功！", 200)
        })
    },
    // 获取订单状态统计数
    getUserOrderSatus: (req, res) => {
        let userId = req.body.id
        db.query('select count(*) as ispay from user_order where userId = ? and is_pay = 0;select count(*) as isdeliver from user_order where userId = ? and is_deliver =1;select count(*) as todeliver from user_order where userId = ? and is_deliver = 0 and is_pay = 1', [userId, userId, userId], function (err, result) {
            if (err) return res.cc(err)
            return res.send({
                code: 200,
                msg: "获取订单状态成功！",
                data: {
                    ispay: result[0][0].ispay,
                    isdeliver: result[1][0].isdeliver,
                    todeliver: result[2][0].todeliver
                }
            })

        })
    },
    // 获取待付款列表
    get2payOrder: (req, res) => {
        let userId = req.body.id
        db.query("select a.id,a.shopId,a.orderNum,a.number,a.createTime,a.order_status,a.is_pay,a.order_sumup,b.goodName,b.priceAgo,b.model,b.price,c.shopName,d.picName from user_order a,goods b,shop c,goods_pic d where userId = ? and a.goodId = b.id and a.shopId = c.id and b.fileId = d.id and a.is_delete = 0 and is_pay = 0 and order_status = 0 order by a.order_status", userId, function (err, result) {
            if (err) return res.cc(err)
            let data = []
            let resByOrderNum = _.groupBy(result, 'orderNum')
            for (item in resByOrderNum) {
                let orderByShop = _.groupBy(resByOrderNum[item], 'shopName')
                for (i2 in orderByShop) {
                    let temp = {
                        'id': resByOrderNum[item][0].id,
                        'orderNum': item,
                        'shopId': orderByShop[i2][0].shopId,
                        'createTime': resByOrderNum[item][0].createTime.split(" ")[0],
                        'shopName': i2,
                        'order_status': resByOrderNum[item][0].order_status,
                        'list': orderByShop[i2]
                    }
                    data.push(temp)
                }

            }
            return res.send({
                code: 200,
                msg: '获取用户订单成功',
                data: data
            })
        })
    },
    // 获取待收货列表
    get2receive: (req, res) => {
        let userId = req.body.id
        db.query("select a.id,a.shopId,a.orderNum,a.number,a.createTime,a.order_status,a.is_pay,a.order_sumup,b.goodName,b.priceAgo,b.model,b.price,c.shopName,d.picName from user_order a,goods b,shop c,goods_pic d where userId = ? and a.goodId = b.id and a.shopId = c.id and b.fileId = d.id and a.is_delete = 0 and is_deliver = 1 and order_status = 0 order by a.order_status", userId, function (err, result) {
            if (err) return res.cc(err)
            let data = []
            let resByOrderNum = _.groupBy(result, 'orderNum')
            for (item in resByOrderNum) {

                let orderByShop = _.groupBy(resByOrderNum[item], 'shopName')
                for (i2 in orderByShop) {
                    let temp = {
                        'id': resByOrderNum[item][0].id,
                        'orderNum': item,
                        'shopId': orderByShop[i2][0].shopId,
                        'createTime': resByOrderNum[item][0].createTime.split(" ")[0],
                        'shopName': i2,
                        'order_status': resByOrderNum[item][0].order_status,
                        'list': orderByShop[i2]
                    }
                    data.push(temp)
                }

            }
            return res.send({
                code: 200,
                msg: '获取用户订单成功',
                data: data
            })
        })
    },
    // 立即付款
    change2deliver: (req, res) => {
        let info = req.body
        db.query("update user_order set is_pay = 1 where userId =? and orderNum = ? and shopId = ?", [info.userId, info.orderNum, info.shopId], function (err, result) {
            if (err) return res.cc(err)
            return res.cc("修改状态成功！", 200)
        })
    },
    // 我的物流
    getOrderExpress: (req, res) => {
        let id = req.body.id
        db.query("select c.picName ,a.is_pay,a.createTime ,a.is_deliver ,a.orderNum,a.shopId,a.expressNum from user_order a,goods b,goods_pic c where a.goodId = b.id and b.fileId = c.id and a.userId = ? and a.is_delete = 0 and a.order_status = 0 ", id, function (err, result) {
            if (err) return res.cc(err)
            let data = []
            for (let i = 0; result.length; i++) {
                let temp = result[i]
                console.log(delayTimes(temp['createTime'], 1));
                data.push(temp)
            }
            return res.send({
                code: 200,
                msg: "获取物流信息成功！",
                data: result
            })
        })
    }
}